<?php
/**
 * 处理视图的一些显示
 */
namespace App\Http\Controllers;

use App\Http\Model\QuestionNaire;
use App\Http\Model\QuestionNaireCash;
use App\Http\Model\QuestionNaireUser;
use App\Http\Model\User;
use App\Server\Helper;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Session;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class IndexController extends Controller
{
    public function test_user(Request $request)
    {
//        $seData = [
//            'u_id' => '1',
//            'username' => 'test',
//            'nic_name' => 'test'
//        ];
//        $request->session()->put('user', $seData);
//
//        //$user = new User();
//        //$re = $user->login('18736007158');
//        $re = Helper::send_post(env('API_PRE').'send_wechat_register_msg',['mobile'=>'18736007158','code'=>'12322222']);
//        dd($re);
        //dd(\Session::get('user'));
        dd($_SERVER);
        $userModel = new User();
        $re = $userModel->bindUser('13525799109','123123','testdev','test','123123','123123123');
        dump($re);
        //return view('test');
    }
    /**
     * 首页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * create by wenQing
     */
    public function index()
    {
        return view('index');
    }
    public function consult()
    {
        return view('consult');
    }
    public function description()
    {
        return view('description');
    }

    /**
     * 医生详情
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * create by wenQing
     */
    public function doctorInfo()
    {
        return view('doctorInfo');
    }
    public function doctorList()
    {
        return view('doctorList');
    }
    public function Earnings()
    {
        return view('Earnings');
    }
    public function feedback()
    {
        return view('feedback');
    }
    public function kiting()
    {
        return view('kiting');
    }
    public function mine()
    {
        return view('mine');
    }
    public function myattention()
    {
        return view('myattention');
    }
    public function order()
    {
        return view('order');
    }
    public function submitOrder()
    {
        return view('submitOrder');
    }
    public function changeInfo()
    {
        return view('changeInfo');
    }
    public function changeNicName()
    {
        return view('changeNicName');
    }
    public function changePhoneNumber()
    {
        return view('changePhoneNumber');
    }
    public function diaryBook()
    {
        return view('diaryBook');
    }
    public function orderSuccess()
    {
        return view('orderSuccess');
    }
    public function pay()
    {
        $user = session('wechat.oauth_user');
        return view('pay')->with('open_id',$user->id)->with('appid',env('WECHAT_APPID'));
    }
    public function orderPay()
    {
        return view('orderPay');
    }
    public function searchDoctor()
    {
        return view('searchDoctor');
    }
    public function changePassword()
    {
        return view('changePassword');
    }
    public function writeDairy()
    {
        return view('writeDairy');
    }
    public function hairDairy()
    {
        return view('hairDairy');
    }
    public function doctorJoin()
    {
        return view('doctorJoin');
    }

    /**
     * 选择界面
     * @return $this
     * create by wenQing
     */
    public function questionJudge()
    {
        $uid = \Session::get('user.u_id');
        $cashId = env('CASH_ID');

        $re = QuestionNaireUser::where('cash_id',$cashId)->where('u_id',$uid)->first();
        $time = time() - strtotime($re->created_at);
        if($time < 60)
        {
            $time_str = $time.'秒';
        }
        elseif(($time/60) < 60)
        {
            $time_str = (int)($time/60).'分钟';
        }
        elseif(($time/60/60) < 60)
        {
            $time_str = (int)($time/60/60).'小时';
        }
        elseif(($time/60/60/24) < 60)
        {
            $time_str = (int)($time/60/60/24).'天';
        }

        return view('questionJudge')->with('time_str',$time_str);
    }

    /**
     * 问卷结果界面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     * create by wenQing
     */
    public function questionReport(Request $request)
    {
        //跳转到中间界面
//        if(empty(session('is_question')) && empty($request->input('is_check_html')))
//        {
//            return redirect('questionJudge.html');
//        }

//        $reCord = Redis::get(\Session::get('user.u_id').'question');
//        if(empty($reCord))
//        {
//            return redirect('question.html');
//        }
//        else
//        {
//            $arr = \GuzzleHttp\json_decode($reCord,true);
//            $point = $arr['point'];
//            $level = $arr['level'];
//        }

        $point = '0.8';
        $level = 1;
        return view('questionReport',['point' => json_encode($point),'level' => $level]);
    }

    /**
     * 调查问卷界面显示
     * create by wenQing
     */
    public function question(Request $request)
    {
        //判断一下跳转
        if(empty($request->input('is_callback')))
        {
            $reCord = Redis::get(\Session::get('user.u_id').'question');
            if($reCord)
            {
                return redirect('questionReport.html')->with('reCord',$reCord);
            }
        }
        //处理提交的数据
        if($request->method() == 'POST')
        {
            $this->uploadImage(); //上传图片
            $questionUser = new QuestionNaireUser();
            if($request->input('is_callback') == 'true')
            {
                //这里是重新填写数据的界面
                QuestionNaireUser::where('u_id',\Session::get('user.u_id'))->where('cash_id',env('CASH_ID'))->delete(); //删除一起的数据
            }

            $questionUser->insertUserRecord($request->input('entry'),\Session::get('user.u_id'));
            $re = $questionUser->countRecordOption('',\Session::get('user.u_id'));
            Redis::set(\Session::get('user.u_id').'question',json_encode($re));

            return redirect('questionReport.html')->with('is_question','true'); //显示在结果界面
        }

        //获取问卷的记录
        $cash = QuestionNaireCash::find(env('CASH_ID'))->toArray(); //默认取出第一个问卷的数据
        $questionIds = $cash['question_id_str']; //问卷包含的问题id
        $questions = QuestionNaire::whereIn('id',explode(',',$questionIds))->get()->toArray();
        //获取问题以及选项的数据
        foreach($questions as $k => $v)
        {
            $questions[$k]['option'] = QuestionNaire::find($v['id'])->option->toArray();
        }
        $questionArr = $questions; //获取数据

        //修改一下数据
        foreach($questionArr as $k => $option)
        {
            //类型显示
            switch($option['type'])
            {
                case '1':
                    $questionArr[$k]['type_name'] = 'DropDown'; //单选下拉框
                    $questionArr[$k]['file_name'] = 'field-drop-down'; //单选下拉框
                    break;
                case '2':
                    $questionArr[$k]['type_name'] = 'CheckBox'; //多选checkbox
                    $questionArr[$k]['file_name'] = 'field-check-box'; //多选checkbox
                    break;
                case '3':
                    $questionArr[$k]['type_name'] = 'TextField'; //单文本输入
                    $questionArr[$k]['file_name'] = 'field-drop-down'; //单选下拉框
                    break;
                case '4':
                    $questionArr[$k]['type_name'] = 'TextFields'; //多行文本输入
                    $questionArr[$k]['file_name'] = 'field-drop-down'; //单选下拉框
                    break;
                case '5':
                    $questionArr[$k]['type_name'] = 'ImageRadioButton'; //图片单选
                    $questionArr[$k]['file_name'] = 'field-image-radio-button'; //图片单选
                    break;
            }
        }

        return view('question')->with('question',$questionArr)->with('is_callback',$request->input('is_callback'));
    }

    /**
     * 上传图片
     * create by wenQing
     * @throws \Exception
     */
    public function uploadImage()
    {
        $file = Input::file('image-frame');
        if($file)
        {
            //检验一下上传的文件是否有效.
            $entension = $file -> getClientOriginalExtension(); //上传文件的后缀.

            // 上传到七牛后保存的文件名
            $key = 'user-frame-'.time().'.'.$entension;
            $file -> move('uploads',$key);
            $newPath = './uploads/'.$key;

            $ak = '9BrolDMS4-iOwAlWu3OHNKfxA7ql6fWjfIimAsF_';
            $sk = '3eT5jKoSBGx4KcNS4lo1iNP8yqlHbSdPpg2j86Zn';
            $auth = new Auth($ak,$sk);
            $bucket = 'fafu';
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 生成上传 Token
            $token = $auth->uploadToken($bucket);
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $newPath);

            //插入数据
            $question_user = new QuestionNaireUser();
            $question_user->option = $key; //保存七牛地址
            $question_user->u_id = \Session::get('user.u_id'); //用户id
            $question_user->save();
        }
        return $key;
    }

    public function question_test(Request $request)
    {
        if($request->method() == 'POST')
        {
            $file = Input::file('image-frame');
            //检验一下上传的文件是否有效.
            $entension = $file -> getClientOriginalExtension(); //上传文件的后缀.

            // 上传到七牛后保存的文件名
            $key = 'user-frame-'.time().'.'.$entension;
            $file -> move('uploads',$key);
            $newPath = './uploads/'.$key;

            $ak = '9BrolDMS4-iOwAlWu3OHNKfxA7ql6fWjfIimAsF_';
            $sk = '3eT5jKoSBGx4KcNS4lo1iNP8yqlHbSdPpg2j86Zn';
            $auth = new Auth($ak,$sk);
            $bucket = 'fafu';
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 生成上传 Token
            $token = $auth->uploadToken($bucket);
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $newPath);
        }
        //获取问卷的记录
        $cash = QuestionNaireCash::find(env('CASH_ID'))->toArray(); //默认取出第一个问卷的数据
        $questionIds = $cash['question_id_str']; //问卷包含的问题id
        $questions = QuestionNaire::whereIn('id',explode(',',$questionIds))->get()->toArray();
        //获取问题以及选项的数据
        foreach($questions as $k => $v)
        {
            $questions[$k]['option'] = QuestionNaire::find($v['id'])->option->toArray();
        }
        $questionArr = $questions; //获取数据

        //修改一下数据
        foreach($questionArr as $k => $option)
        {
            //类型显示
            switch($option['type'])
            {
                case '1':
                    $questionArr[$k]['type_name'] = 'DropDown'; //单选下拉框
                    $questionArr[$k]['file_name'] = 'field-drop-down'; //单选下拉框
                    break;
                case '2':
                    $questionArr[$k]['type_name'] = 'CheckBox'; //多选checkbox
                    $questionArr[$k]['file_name'] = 'field-check-box'; //多选checkbox
                    break;
                case '3':
                    $questionArr[$k]['type_name'] = 'TextField'; //单文本输入
                    $questionArr[$k]['file_name'] = 'field-drop-down'; //单选下拉框
                    break;
                case '4':
                    $questionArr[$k]['type_name'] = 'TextFields'; //多行文本输入
                    $questionArr[$k]['file_name'] = 'field-drop-down'; //单选下拉框
                    break;
                case '5':
                    $questionArr[$k]['type_name'] = 'ImageRadioButton'; //图片单选
                    $questionArr[$k]['file_name'] = 'field-image-radio-button'; //图片单选
                    break;
            }
        }

        return view('question')->with('question',$questionArr)->with('is_callback',$request->input('is_callback'));
    }
}
